package com.heima.wemedia.service.impl;

import com.heima.apis.article.ArticleClient;
import com.heima.apis.user.UserFeign;
import com.heima.apis.wemedia.WemediaFeign;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.*;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.ApCommentRepayVo;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmManageServiceImpl implements WmManageService {
    @Autowired
    private ArticleClient articleClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findNewsComments(WmFindNewsCommentsDto dto) {
        PageResponseResult responseResult = articleClient.findNewsComments(dto);
        return responseResult;
    }

    /**
     * 打开和关闭评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateCommentStatus(WmUpdateCommentStatusDto dto) {
        return articleClient.updateStatus(dto);
    }

    /**
     * 查看评论回复列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult commentRepayList(WmManageDto dto) {
        dto.checkParam();
        List<ApCommentRepayVo> list = new ArrayList<>();

        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);

        for (ApComment apComment : apComments) {
            ApCommentRepayVo vo = new ApCommentRepayVo();
            vo.setApComments(apComment);
            Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId()));
            query2.with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query2, ApCommentRepay.class);
            vo.setApCommentRepays(apCommentRepays);

            list.add(vo);
        }

        return ResponseResult.okResult(list);
    }

    /**
     * 作者回复评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult commentRepay(WmCommentRepayDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论字数不能超过140个字!");
        }
        //获取自媒体人信息
        WmUser wmUser = WmThreadLocalUtil.getUser();
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        if (dbUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //文本垃圾检测
        List<WmSensitive> wmSensitiveList = wemediaFeign.getAll();
        List<String> sensitiveList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitiveList);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(dto.getContent());
        if (map.size() > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前评论中存在违规内容" + map);
        }
        //获取app端用户信息
        ApUser apUser = userFeign.findById(dbUser.getApUserId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }

        //保存评论回复
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setLikes(0);
        //添加评论回复表
        mongoTemplate.insert(apCommentRepay);
        //评论表回复加一
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(apCommentRepay);
    }

    /**
     * 作者点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = WmThreadLocalUtil.getUser();
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        if (dbUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = userFeign.findById(dbUser.getApUserId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (dto.getOperation() == 0) {
            //点赞 评论表 点赞加一
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
            //点赞表 新增
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setAuthorId(apUser.getId());
            mongoTemplate.save(apCommentLike);
        } else {
            //取消点赞  评论表  点赞减一
            apComment.setLikes(apComment.getLikes() == 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            //删除点赞表
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(dto.getCommentId())), ApCommentLike.class);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 作者删除评论
     *
     * @param commentId
     * @return
     */
    @Override
    public ResponseResult delCommentById(String commentId) {
        if (commentId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除评论表
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentId)), ApComment.class);
        //删除评论点赞表
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), ApCommentLike.class);

        //删除评论的所有回复
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), ApCommentRepay.class);

        //清空批量回复点赞表
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(Query.query(Criteria.where("commentId").is(commentId)), ApCommentRepay.class);
        if (apCommentRepayList != null) {
            for (ApCommentRepay apCommentRepay : apCommentRepayList) {
                mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apCommentRepay.getId())), ApCommentRepayLike.class);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 作者删除评论回复
     *
     * @param commentRepayId
     * @return
     */
    @Override
    public ResponseResult delCommentRepayById(String commentRepayId) {
        if (commentRepayId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除评论回复表
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentRepayId)), ApCommentRepay.class);
        //清空评论回复点赞表
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentRepayId)), ApCommentRepayLike.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
